<?php


namespace App\Libraries\Weixin;

class Weixin
{
    /**
     *
     * 网页授权接口微信服务器返回的数据，返回样例如下
     * {
     *  "access_token":"ACCESS_TOKEN",
     *  "expires_in":7200,
     *  "refresh_token":"REFRESH_TOKEN",
     *  "openid":"OPENID",
     *  "scope":"SCOPE",
     *  "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
     * }
     * 其中access_token可用于获取共享收货地址
     * openid是微信支付jsapi支付接口必须的参数
     * @var array
     */
    public $data = null;
    private static $instance;

    /**
     * 创建单例
     * @return mixed
     */
    public static function singleton(){
        if(!(self::$instance instanceof self))
        {
            self::$instance = new self;
        }
        return self::$instance;
    }

    /**
     *
     * 通过跳转获取用户的openid，跳转流程如下：
     * 1、设置自己需要调回的url及其其他参数，跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize
     * 2、微信服务处理完成之后会跳转回用户redirect_uri地址，此时会带上一些参数，如：code
     *
     * @return 用户的openid
     */
//    public function GetOpenid()
//    {
//
//        //通过code获得openid
//        if (!isset($_GET['code'])){
//
//
//            //触发微信返回code码
//            //$baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING']);
//
//            $baseUrl = urlencode(HTTP_SERVER."index.php?route=account/login/weChatOauthCallBack");
//            //echo 'http://www.suubuy.cn/catalog/controller/checkout/wxpayconfirm.php';
//            //exit;
//            $url = $this->CreateOauthUrlForCode($baseUrl);
//            //echo $url;
//            //exit;
//
//            Header("Location: $url");
//            exit();
//        } else {
//            //获取code码，以获取openid
//            $code = $_GET['code'];
//            $url = $this->__CreateOauthUrlForOpenid($code);
//            $data = $this->HttpGet($url);
//            $data = json_decode($data, true);
//            if(isset($data['openid']) && isset($data['access_token'])){
//                return $data;
//            }
//            return false;
//        }
//    }

    /**
     * 获取微信用户详细资料
     * @param $params
     * @return bool|mixed|null|openid
     */
    public function GetUserDetail($params){
        $url = $this->__CreateOauthUrlForUserDetail($params['access_token'], $params['openid']);
        $data = $this->HttpGet($url);
        $data = json_decode($data, true);
        if(isset($data['nickname'])){
            return $data;
        }
        return false;
    }


    /**
     *
     * 通过code从工作平台获取openid机器access_token
     * @param string $url
     *
     * @return openid
     */
    public function HttpGet($url)
    {

        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }



    /**
     *
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     *
     * @return 返回构造好的url
     */
//    public function CreateOauthUrlForCode($redirectUrl)
//    {
//        $urlObj["appid"] = WxLoginConfig::APPID;
//        $urlObj["redirect_uri"] = "$redirectUrl";
//        $urlObj["response_type"] = "code";
//        $urlObj["scope"] = "snsapi_userinfo";
//        $urlObj["state"] = "STATE"."#wechat_redirect";
//        $bizString = $this->ToUrlParams($urlObj);
//        //echo "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
//        //exit;
//        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
//    }

    /**
     *
     * 拼接签名字符串
     * @param array $urlObj
     *
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     *
     * 构造获取open和access_toke的url地址
     * @param string $code，微信跳转带回的code
     *
     * @return 请求的url
     */
//    private function __CreateOauthUrlForOpenid($code)
//    {
//        $urlObj["appid"] = WxLoginConfig::APPID;
//        $urlObj["secret"] = WxLoginConfig::APPSECRET;
//        $urlObj["code"] = $code;
//        $urlObj["grant_type"] = "authorization_code";
//        $bizString = $this->ToUrlParams($urlObj);
//        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
//    }

    private function __CreateOauthUrlForUserDetail($access_token, $openid){
        $urlObj['access_token'] = $access_token;
        $urlObj['openid'] = $openid;
        $urlObj['lang'] = 'zh_CN';
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/userinfo?".$bizString;
    }
}